//
//  ChatSettingTableViewController.m
//  MooreDoll
//
//  Created by 郭景豪 on 2014/12/26.
//  Copyright (c) 2014年 Tank. All rights reserved.
//

#import "ChatSettingTableViewController.h"
#import "UserInfoFor0Cell.h"
#import "UserInfoFor1Cell.h"
#import "UserInfoFor2Cell.h"
#import "UserInfoFor3Cell.h"
#import "NetworkManager.h"
#import "RoundImage.h"
#import "WinkAlertView.h"
#import "WriteToFileImage.h"
#import "VersionsViewController.h"
#import "MessageStatus.h"
@interface ChatSettingTableViewController ()<UserInfoFor0CellDelegate,CheckToyUpdateDelegate>

@end

@implementation ChatSettingTableViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    
    NSLog(@"%@",self.getJid);
    
    //取得娃娃資料
    NSArray *array =[[NetworkManager sharedInstance]coreDataSearchWithEntityName:@"Roster" Predicate:[NSString stringWithFormat:@"jid CONTAINS[cd] '%@'",self.getJid] SortBy:nil];
    
    self.toyInfo = array.firstObject;
    
    NSLog(@"%@",self.toyInfo);
    
    self.checkAlertView = [[UIAlertView alloc]initWithTitle:NSLocalizedString(@"檢查娃娃版號中", nil) message:NSLocalizedString(@"請確認娃娃是否有開啟", nil) delegate:nil cancelButtonTitle:nil otherButtonTitles: nil];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - Table view data source

#pragma mark - Table view data source
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    //設定第一個cell 高度 （使用者圖片資料）
    if (indexPath.row==0) {
        //依照螢幕寬度來設定Cell 高度
        return CGRectGetWidth([UIScreen mainScreen].bounds)*0.400;
    }
    
    //依照螢幕寬度來設定Cell 高度
    return CGRectGetWidth([UIScreen mainScreen].bounds)*0.1375;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    // Return the number of rows in the section.
    return 7;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    switch (indexPath.row) {
        case 0:
            return [self onePage:tableView cellForIndexPath:indexPath];
            break;
        case 1:
            return [self twoPage:tableView cellForIndexPath:indexPath];
            
            break;
        case 2:
            return [self ThreePage:tableView cellForIndexPath:indexPath];
            
            break;
        case 3:
            return [self FourPage:tableView cellForIndexPath:indexPath];
            break;
        case 4:
            return [self FivePage:tableView cellForIndexPath:indexPath];
            break;
        case 5:
            return [self SixPage:tableView cellForIndexPath:indexPath];
            break;
        case 6:
            return [self SevenPage:tableView cellForIndexPath:indexPath];
            break;
        default:
            return nil;
            break;
    }
    // Configure the cell...
    
}
-(UserInfoFor0Cell *)onePage:(UITableView *)tableView cellForIndexPath:(NSIndexPath *)indexPath
{
    UserInfoFor0Cell *cell = (UserInfoFor0Cell*)[tableView dequeueReusableCellWithIdentifier:@"UserInfoFor0Cell"];
    
    if (cell == nil) {
        [tableView registerNib:[UINib nibWithNibName:@"UserInfoFor0Cell" bundle:nil] forCellReuseIdentifier:@"UserInfoFor0Cell"];
        cell = [tableView dequeueReusableCellWithIdentifier:@"UserInfoFor0Cell"];
    }
    /*
     jid = "toyf30d84a702234c398@bbserver-virtualbox";
     nickeName = "";
     owner = "<relationship fault: 0x17042f760 'owner'>";
     photoPath = "";
     type = user;
     */
    if (self.toyInfo.photoPath) {
        [cell.photoButton setImage:[RoundImage maskImage:[UIImage imageWithContentsOfFile:self.toyInfo.photoPath] withMask:[UIImage imageNamed:@"mask"]] forState:UIControlStateNormal];
    }else
    {
        [cell.photoButton setImage:[RoundImage maskImage:[UIImage imageNamed:@"userImage"] withMask:[UIImage imageNamed:@"mask"]] forState:UIControlStateNormal];
    }
    if (cell.delegate != self) {
        cell.delegate = self;
    }
    return cell;
}
-(UserInfoFor1Cell *)twoPage:(UITableView *)tableView cellForIndexPath:(NSIndexPath *)indexPath
{
    UserInfoFor1Cell *cell = (UserInfoFor1Cell*)[tableView dequeueReusableCellWithIdentifier:@"UserInfoFor1Cell"];
    
    if (cell == nil) {
        
        [tableView registerNib:[UINib nibWithNibName:@"UserInfoFor1Cell" bundle:nil] forCellReuseIdentifier:@"UserInfoFor1Cell"];
        
        cell = [tableView dequeueReusableCellWithIdentifier:@"UserInfoFor1Cell"];
    }
    
    cell.textLabel.text = @"暱稱";
    cell.detailTextLabel.text = self.toyInfo.nickeName?self.toyInfo.nickeName:@"無名氏";
    
    return cell;
}
-(UserInfoFor3Cell *)ThreePage:(UITableView *)tableView cellForIndexPath:(NSIndexPath *)indexPath
{
    UserInfoFor3Cell *cell = (UserInfoFor3Cell*)[tableView dequeueReusableCellWithIdentifier:@"UserInfoFor3Cell"];
    
    if (cell == nil) {
        
        [tableView registerNib:[UINib nibWithNibName:@"UserInfoFor3Cell" bundle:nil] forCellReuseIdentifier:@"UserInfoFor3Cell"];
        
        cell = [tableView dequeueReusableCellWithIdentifier:@"UserInfoFor3Cell"];
    }
    cell.textLabel.text = @"無線網路設置";
    
    return cell;
}
-(UserInfoFor3Cell *)FourPage:(UITableView *)tableView cellForIndexPath:(NSIndexPath *)indexPath
{
    UserInfoFor3Cell *cell = (UserInfoFor3Cell*)[tableView dequeueReusableCellWithIdentifier:@"UserInfoFor3Cell"];
    
    if (cell == nil) {
        
        [tableView registerNib:[UINib nibWithNibName:@"UserInfoFor3Cell" bundle:nil] forCellReuseIdentifier:@"UserInfoFor3Cell"];
        
        cell = [tableView dequeueReusableCellWithIdentifier:@"UserInfoFor3Cell"];
    }
    cell.textLabel.text = @"提醒設定";
    return cell;
}
-(UserInfoFor3Cell *)FivePage:(UITableView *)tableView cellForIndexPath:(NSIndexPath *)indexPath
{
    UserInfoFor3Cell *cell = (UserInfoFor3Cell*)[tableView dequeueReusableCellWithIdentifier:@"UserInfoFor3Cell"];
    
    if (cell == nil) {
        
        [tableView registerNib:[UINib nibWithNibName:@"UserInfoFor3Cell" bundle:nil] forCellReuseIdentifier:@"UserInfoFor3Cell"];
        
        cell = [tableView dequeueReusableCellWithIdentifier:@"UserInfoFor3Cell"];
    }
    
    cell.textLabel.text = @"娃娃勿擾模式";
    
    return cell;
}

-(UserInfoFor3Cell *)SixPage:(UITableView *)tableView cellForIndexPath:(NSIndexPath *)indexPath
{
    UserInfoFor3Cell *cell = (UserInfoFor3Cell*)[tableView dequeueReusableCellWithIdentifier:@"UserInfoFor3Cell"];
    
    if (cell == nil) {
        
        [tableView registerNib:[UINib nibWithNibName:@"UserInfoFor3Cell" bundle:nil] forCellReuseIdentifier:@"UserInfoFor3Cell"];
        
        cell = [tableView dequeueReusableCellWithIdentifier:@"UserInfoFor3Cell"];
    }
    
    cell.textLabel.text = @"刪除聊天紀錄";
    
    return cell;
}

-(UserInfoFor3Cell *)SevenPage:(UITableView *)tableView cellForIndexPath:(NSIndexPath *)indexPath
{
    UserInfoFor3Cell *cell = (UserInfoFor3Cell*)[tableView dequeueReusableCellWithIdentifier:@"UserInfoFor3Cell"];
    
    if (cell == nil) {
        
        [tableView registerNib:[UINib nibWithNibName:@"UserInfoFor3Cell" bundle:nil] forCellReuseIdentifier:@"UserInfoFor3Cell"];
        
        cell = [tableView dequeueReusableCellWithIdentifier:@"UserInfoFor3Cell"];
    }
    
    cell.textLabel.text = @"娃娃更新";
    
    return cell;
}


-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.row==6) {
        
        NSString *messageContent = [NSString stringWithFormat:@"OTASTATUS %@",[self.toyInfo.nickeName stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
        
        [self.checkAlertView show];
        
        [MessageStatus sharedInstance].checkToyUpdateDelegate = self;
        
        xclient_message_send((char*) [self.toyInfo.jid UTF8String], (char*) [messageContent UTF8String]);
        
    }
}
#pragma mark CheckToyUpdate
-(void)getCheckToyUpdateInfo:(NSMutableDictionary *)InfoResults
{
    NSLog(@"%@",InfoResults);
            [self getNewVersion:InfoResults completionBlock:^(NSDictionary *response) {
                
                [self.checkAlertView dismissWithClickedButtonIndex:0 animated:YES];
                
                if (response) {
                    NSLog(@"%@",response);
                    if ([response objectForKey:@"version"]) {
                        [self compareAndContrastNewVersionWithOldVersion:InfoResults NewVersion:response completionBlock:^(BOOL isNew, NSDictionary *version) {
                            
                            VersionsViewController *versionsVC = [self.storyboard instantiateViewControllerWithIdentifier:@"VersionsViewController"];
                            versionsVC.isNew = isNew;
                            versionsVC.versionsDictionary = version;
                            versionsVC.toyInfo = self.toyInfo;
                            [self.navigationController pushViewController:versionsVC animated:YES];
                        }];
                    }
                }
                
            } failureBlock:^(NSError *error) {
                [self.checkAlertView dismissWithClickedButtonIndex:0 animated:YES];

                [WinkAlertView _showAlertViewWithTitle:@"失敗" content:@"網路連結失敗" cancelButtonTitle:@"確認" showTime:3.0f];
                
            }];
    
}

-(void)compareAndContrastNewVersionWithOldVersion:(NSDictionary *)OldVersion NewVersion:(NSDictionary *)NewVersion completionBlock:(void(^)(BOOL isNew,NSDictionary* version))completion
{
    NSString *versionOld = [OldVersion[@"runver"] stringByReplacingOccurrencesOfString:@"." withString:@""];
    NSString *versionNew = [NewVersion[@"version"] stringByReplacingOccurrencesOfString:@"." withString:@""];
    if ([versionNew integerValue]>[versionOld integerValue]) {
        if (completion) {
            completion(YES,NewVersion);
        }
    }else
    {
        if (completion) {
            completion(NO,NewVersion);
        }
    }
}

-(void)getNewVersion:(NSDictionary *)toyVersion completionBlock:(void(^)(NSDictionary *response))completion failureBlock:(void(^)(NSError *error))failureBlock
{
    AFHTTPRequestOperationManager* afManager = [AFHTTPRequestOperationManager manager];
    
    afManager.responseSerializer = [AFJSONResponseSerializer serializerWithReadingOptions:NSJSONReadingAllowFragments];
    
    afManager.responseSerializer.acceptableContentTypes = [afManager.responseSerializer.acceptableContentTypes setByAddingObject:@"text/plain"];
    
    NSLog(@"%@",toyVersion[@"hwver"]);
    NSDictionary *parameters = @{@"type":@"ota",@"secret":@"openfire",@"hw":toyVersion[@"hwver"],@"jid":self.toyInfo.jid_noDomain};
    
    NSLog(@"%@",parameters);
    
    [afManager POST:MD_SERVER_API parameters:parameters success:^(AFHTTPRequestOperation *operation, id responseObject) {
        
        if (completion) {
            completion(responseObject);
        }
        
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        if (failureBlock) {
            failureBlock(error);
        }
    }];
    
}


/*
 process toy update
 */
-(void)changeToyUpadeInfoWithInfo:(NSMutableDictionary *)info completionBlock:(void(^)(NSDictionary *result))compint failureBlock:(void(^)(void))failureBlock
{
    NSMutableDictionary *results = [@{}mutableCopy];
    
    NSArray *array = [info[@"message_recv"]componentsSeparatedByString:@" "];
    /*
     messagestatus,
     "type=OTASTATUS",
     "auto=0",
     "status=N",
     "hwver=2",
     "runver=0.12.141211.526",
     "downloadver="
     */
    
    for (int i = 1 ; i <= array.count-1 ; i++) {
        
        NSArray *array2 = [array[i] componentsSeparatedByString:@"="];
        
        [results setObject:array2[1] forKey:array2[0]];
    }
    
    if (results.count >0) {
        
        if (compint) {
            compint(results);
        }
        
    }else
    {
        if (failureBlock) {
            failureBlock();
        }
    }
}

#pragma mark 大頭貼 delegate
-(void)cellTakePhotoButtonOpenCamera:(UIImagePickerController *)camera
{
    [self presentViewController:camera animated:YES completion:nil];
}
-(void)cellTakePhotoButtonOpenPhotoLibrary:(UIImagePickerController *)PhotoLibrary
{
    [self presentViewController:PhotoLibrary animated:YES completion:nil];
}
-(void)cellTakePhotoAlertDismissVC
{
    [self dismissViewControllerAnimated:YES completion:^{
        
        dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC));
        dispatch_after(popTime, dispatch_get_main_queue(), ^(void){
            
            UserInfoFor0Cell *cell = (UserInfoFor0Cell *)[self.tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:0]];
            //            UserInfoFor0Cell *cell = [[self.tableView visibleCells]firstObject];
            
            NSString *userImagePath;
            
            if (cell.photoButton.imageView.image != nil) {
                //儲存使用者的圖片
                
                userImagePath = [[WriteToFileImage sharedInstance]GetAndWriteToFileImage:cell.photoButton.imageView.image fileName:@"toy"];
            }else
            {
                //儲存使用者的圖片
                userImagePath = [[WriteToFileImage sharedInstance]GetAndWriteToFileImage:[UIImage imageNamed:@"dficon_modo"] fileName:@"toy"];
            }
            
            if (userImagePath != nil) {
                //將名字還有 圖片路徑包進字典
                NSDictionary *toyDict = @{@"toyJid":self.getJid,@"toyNickName":self.toyInfo.nickeName,@"toyImage":userImagePath};
                
                [[XMPPSharedInstance sharedInstance]changeToyVcard:toyDict];
                //執行變更名字和照片
            }
        });
    }];
}
-(void)cellTakePhotoClance
{
    [self dismissViewControllerAnimated:YES completion:nil];
    
}
@end
